from flask import Flask
from os.path import *
import sys

from flask_cors import CORS
from rediscluster import RedisCluster

# 将common路径加入模块查询路径
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis


BASE_DIR = dirname(dirname(abspath(__file__)))
sys.path.insert(0, BASE_DIR + '/common')

from app.settings.config import config_dict
from utils.constants import EXTRA_ENV_COINFIG


# sqlalchemy组件对象
db = SQLAlchemy()


# redis数据库操作对象
redis_cluster = None  # type: StrictRedis


def register_bp(app:Flask):
    """注册蓝图"""
    # 用户蓝图
    from app.resources.user import user_bp  # 进行局部导入, 避免组件没有初始化完成
    app.register_blueprint(user_bp)

    # 新闻蓝图
    from app.resources.article import article_bp
    app.register_blueprint(article_bp)



def register_extensions(app):
    """组件初始化"""
    global redis_cluster
    # MySQL组件初始化
    db.init_app(app)
    # redis组件初始化
    # redis_client = StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], decode_responses=True)
    redis_cluster = RedisCluster(startup_nodes=app.config['STARTUP_NODES'],decode_responses=True)
    # 路由转换器
    from utils.converters import register_converters
    register_converters(app)
    # 数据迁移组件初始化
    Migrate(app, db)

    # 导入模型类
    from models import user
    from models import article

    # 添加请求钩子
    from utils.middlewares import get_userinfo
    app.before_request(get_userinfo)

    CORS(app,supports_credentials=True) # supports_credentials 语序跨域传输cookie

def create_flask_app(type):
    """创建flask应用"""

    # 创建flask应用
    app = Flask(__name__)
    # 根据类型加载配置子类
    config_class = config_dict[type]
    # 先加载默认配置
    app.config.from_object(config_class)
    # 再加载额外配置 环境变量指定的那个文件
    app.config.from_envvar(EXTRA_ENV_COINFIG,silent=False)

    # 返回应用
    return app


def create_app(type):
    """创建应用 和 组件初始化"""

    # 创建flask应用
    app = create_flask_app(type)
    # 组件初始化
    register_extensions(app)
    # 蓝图注册
    register_bp(app)


    return app